﻿#include "dxstdafx.h"
#include "FNTFontManager.h"

void CFNTFontManager::LoadFntFile(IDirect3DDevice9* pd3dDevice)
{
	HRESULT hr = S_OK;
	std::wstring szRcPathOut;
	CommonFunc::RelativePath2FullPath(L"\\ResFile\\Support\\Font\\", szRcPathOut);
	std::list<std::wstring> listFileName;
	CommonFunc::GetFolderFile(szRcPathOut, L"fnt", listFileName);

	for (const auto& it : listFileName)
	{
		FontCharSet st;
		parseTextFntFile(szRcPathOut + it + L".fnt", st);
		// 装入tga纹理
		D3DXIMAGE_INFO image_info;
		std::wstring TexturePathWithoutFormat = szRcPathOut + it;
		std::wstring TextureFullPath = TexturePathWithoutFormat + L".tga";
		// 读文件信息
		if (FAILED(D3DXGetImageInfoFromFile(TextureFullPath.c_str(), &image_info)))
		{
			// 可能不是tga格式 就去试试dds
			TextureFullPath = TexturePathWithoutFormat + L".dds";
			V(D3DXGetImageInfoFromFile(TextureFullPath.c_str(), &image_info));
		}
		V(D3DXCreateTextureFromFileEx(pd3dDevice, TextureFullPath.c_str(), image_info.Width, image_info.Height,
			image_info.MipLevels, 0, image_info.Format, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0,
			NULL, NULL, &st.TextureBitMap));
		st.bitmapWidth = image_info.Width;
		st.bitmapHeight = image_info.Height;
		m_map_FontCharSet.insert(std::make_pair(it, st));
	}
}

const FontCharSet* CFNTFontManager::GetFontCharSet(const std::wstring& FontName) const
{
	auto iterFind = m_map_FontCharSet.find(FontName);
	if (m_map_FontCharSet.end() != iterFind)
	{
		return &iterFind->second;
	}
	return nullptr;
}

void CFNTFontManager::OnD3D9DestroyDevice()
{
	if (m_map_FontCharSet.empty())
	{
		return;
	}
	for (auto& it : m_map_FontCharSet)
	{
		SAFE_RELEASE(it.second.TextureBitMap);
	}
}
